import React, { useState ,useEffect} from "react";
import Dialog from "@knownsec/react-component/dist/Dialog";
import Icon from "@knownsec/react-component/dist/Icon";
import Button from "@knownsec/react-component/dist/Button";
import ReactDOM from 'react-dom';
import cn from 'classnames'

const ConfirmBaseInit = ({ className, message, confirmText = '确认', cancelText = '取消', onConfirm, oncancel, ConfirmDemo }) => {
	const [visible, setVisible] = useState(true)
	const [loading, setLoading] = useState(false)
	const [data, setData] = useState(message?.cusData || {})
	const handleHide = () => {
		setVisible(false)
		if (oncancel) {
			oncancel()
		}
	}

	const handleConfirm = () => {
		if (onConfirm && !loading) {
			setLoading(true)
			onConfirm(() => {
				setLoading(false)
				setVisible(false)
			}, data)
		}
	}
	const cusConfirmDemo=()=>{
		if(!ConfirmDemo){
			return <Button
			type="primary"
			onClick={handleConfirm.bind(this)}
			disabled={loading}
		>
			{confirmText}
		</Button>
		}else{
			return ConfirmDemo
		}
	}
	useEffect(() => {
		if (visible) {
			const de = document.querySelector(".ConfirmBase").nextElementSibling;
			de.style.zIndex = 2003;
			const de2 = document.querySelector(".ConfirmBase")
			de2.style.zIndex = 2004;
			de2.style.width = "500px";
		}
	}, [visible]);
	return (
		visible&&<Dialog visible={visible}
			onhide={handleHide.bind(this)}
			cancelText={cancelText}
			cusConfirm={cusConfirmDemo()}
			confirmText={confirmText}
			pro={true}
			header={(
				<div className={'pr p20'}>
					<Icon type='cancel' onClick={handleHide.bind(this)} className={cn('cp fs20 pa')} style={{ top: '15px', right: '15px' }} />
				</div>
			)}
			className={cn(className,"ConfirmBase")}
		>
			<div className={cn("mb10 pt0 pb0 pl20 pr20 tac")}>
				<Icon type={message?.icon || 'error'} className={cn([message?.iconColor || 'warning-color'], "fs24 mb10 db")} />
				<span>
					{(typeof message?.text === 'function' ? message?.text([data, setData]) : message?.text)  || ''}
				</span>
			</div>
		</Dialog>
	)
}
const ConfirmBase = function (data) {
	const node = document.createElement('div');
	document.body.appendChild(node)
	return ReactDOM.render(<ConfirmBaseInit {...data} />, node)
}

export default ConfirmBase
